﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using DA;

namespace ERP.Membership
{
    public class ERPMembership
    {
        private const string SESSION_COOKIE_NAME = "dotnetivot_erp_user_key";
        private const string SESSION_COOKIE_GUID_KEY_NAME = "userid";
        public enum LoginStatus
        {
            Success,
            UserIsNotExist,
            PasswordNotMatch,
            UserIsLocked,
            UserIsNotActive,
            LoginFailed
        }

        public Tuple<LoginStatus, ERP_Users> Login(string email, string password)
        {
            ERP_Users loggedUser = null;
            using (dotNetivotEntities model = new dotNetivotEntities())
            {
                loggedUser = model.ERP_Users.SingleOrDefault(x => x.EMail.ToLower() == email.ToLower());
            }

            if (loggedUser == null)
                return new Tuple<LoginStatus, ERP_Users>(LoginStatus.UserIsNotExist, null);

            else if (loggedUser.Password != password)
            {
                return new Tuple<LoginStatus, ERP_Users>(LoginStatus.PasswordNotMatch, null);
                /*                loggedERP_Users.LoginAttemps += 1;
                                if (isLocked(loggedERP_Users))
                                //loggedERP_Users.isLockedOut = true; */
            }
            else if (loggedUser.Password == password)
            {
                //loggedERP_Users.LastLogin = DateTime.Now;
                //loggedERP_Users.LoginAttemps = 0;
                //save
                CreatePermanentCookie(loggedUser, SESSION_COOKIE_NAME, SESSION_COOKIE_GUID_KEY_NAME, DateTime.Now.AddMinutes(20));
                return new Tuple<LoginStatus, ERP_Users>(LoginStatus.Success, loggedUser);
            }
            else
            {
                //save
                return new Tuple<LoginStatus, ERP_Users>(LoginStatus.LoginFailed, loggedUser);
            }
        }

        private bool isLocked(ERP_Users loggedERP_Users)
        {
            throw new NotImplementedException();
        }
        public void Logout()
        {
            HttpContext.Current.Session.Remove(SESSION_COOKIE_NAME);
        }
        private void CreatePermanentCookie(ERP_Users ERP_Users, string cookieName, string cookieUserIdKey, DateTime? cookieExpirationTime = null)
        {
            HttpContext.Current.Session.Remove(cookieName);
            HttpContext.Current.Session.Add(cookieName, ERP_Users.UserGuid.Value.ToString());
        }

        public UserData GetCurrentLoggedInUser()
        {
            var objSessionId = HttpContext.Current.Session[SESSION_COOKIE_NAME];
            if (objSessionId == null)
                return null;

            var sessionId = objSessionId.ToString();
            if (string.IsNullOrWhiteSpace(sessionId))
                return null;

            UserData loggedUser = null;
            Guid userGuid;
            if (Guid.TryParse(sessionId, out userGuid))
            {
                using (dotNetivotEntities model = new dotNetivotEntities())
                {
                    ERP_Users user = model.ERP_Users.SingleOrDefault(x => x.UserGuid.Value == userGuid);

                    IEnumerable<int> rolesIds = Enumerable.Empty<int>();

                    if (!string.IsNullOrWhiteSpace(user.Roles))
                    {
                        rolesIds = user.Roles.Split(',').Select(x => int.Parse(x.Trim()));
                    }

                    IEnumerable<ERP_Roles> roles = model.ERP_Roles.Where(x => rolesIds.Contains(x.RoleId));
                    
                    Permission perms = (Permission)Enum.ToObject(typeof(Permission), long.Parse(user.Permissions));
                    foreach (ERP_Roles role in roles)
                    {
                        perms = perms | (Permission)Enum.ToObject(typeof(Permission), long.Parse(role.Permmisions));
                    }

                    loggedUser =
                        new UserData()
                    {
                        UserId = user.UserId,
                        Email = user.EMail,
                        Permissions = perms,
                        Roles = user.Roles.Split(',').Select(x => int.Parse(x)),
                        UserGuid = user.UserGuid.Value

                    };
                }
            }

            return loggedUser;
        }
    }
}
